﻿#include "scripteditor.h"
#include "md5.h"
#include "luaanalyzer.h"
#include "cmainframe.h"

#include <locale>
#include <codecvt>
#include <stack>

wxBEGIN_EVENT_TABLE(MainScriptEditor, wxStyledTextCtrl)
    EVT_SIZE(MainScriptEditor::OnSize)
wxEND_EVENT_TABLE()

MainScriptEditor::MainScriptEditor(wxWindow* parent, wxWindowID id,
    const wxPoint& pos,
    const wxSize& size,
    long style)
    : wxStyledTextCtrl(parent, id, pos, size, style),
      m_mainAuiNotebook(NULL)
{
    m_lastModifiedLine = -1;
    m_isTextModified = false;
    m_isLeftBtnDoublieClick = false;

    // 设置语法解析器为 Lua
    this->SetupLuaSyntaxHighlight();

    // 启用自动补全
    this->AutoCompSetIgnoreCase(true); // 忽略大小写
    this->AutoCompSetAutoHide(false);  // 失去焦点时不自动隐藏
    this->AutoCompSetMaxHeight(10);    // 显示的最大条目数
    this->AutoCompSetSeparator(' ');   // 分隔符

    this->Bind(wxEVT_STC_CHANGE, &MainScriptEditor::OnContentChange, this);
    this->Bind(wxEVT_STC_MODIFIED, &MainScriptEditor::OnStyledTextModified, this);
    this->Bind(wxEVT_STC_UPDATEUI, &MainScriptEditor::OnSelectionChanged, this);
    this->Bind(wxEVT_STC_CHARADDED, &MainScriptEditor::OnCharAdded, this);
    this->Bind(wxEVT_LEFT_DCLICK, &MainScriptEditor::OnLeftDoubleClick, this);
    this->Bind(wxEVT_STC_AUTOCOMP_SELECTION_CHANGE, &MainScriptEditor::OnAutocompSelectionChange, this);
    this->Bind(wxEVT_STC_AUTOCOMP_CANCELLED, &MainScriptEditor::OnAutocompCancelled, this);
    this->Bind(wxEVT_MOTION, &MainScriptEditor::OnMouseMove, this);
    this->Bind(wxEVT_STC_MARGINCLICK, &MainScriptEditor::OnMarginClick, this);
    m_hoverTimer.Bind(wxEVT_TIMER, &MainScriptEditor::OnHoverTimer, this);
}

MainScriptEditor::~MainScriptEditor()
{

}

void MainScriptEditor::SetupLuaSyntaxHighlight(void)
{
    // 设置语法解析器为 Lua
    this->SetLexer(wxSTC_LEX_LUA);

    // 设置默认样式
    this->StyleResetDefault();
    this->StyleSetSize(wxSTC_STYLE_DEFAULT, 10);
    this->StyleSetForeground(wxSTC_STYLE_DEFAULT, wxColour(0, 0, 0));
    this->StyleSetBackground(wxSTC_STYLE_DEFAULT, wxColour(255, 255, 255));
    this->StyleClearAll();

    int indicatorNum = 8; // 使用一个不常用的指示器编号

    // 设置指示器样式
    this->IndicatorSetStyle(indicatorNum, wxSTC_INDIC_STRAIGHTBOX);
    this->IndicatorSetForeground(indicatorNum, wxColour(255, 255, 0)); // 黄色高亮
    this->IndicatorSetUnder(indicatorNum, true);
    this->IndicatorSetAlpha(indicatorNum, 100); // 半透明

    // 设置行号
    this->SetMarginWidth(0, 30);
    this->StyleSetForeground(wxSTC_STYLE_LINENUMBER, wxColour(75, 75, 75));
    this->StyleSetBackground(wxSTC_STYLE_LINENUMBER, wxColour(220, 220, 220));
    this->SetMarginType(0, wxSTC_MARGIN_NUMBER);

    // 设置 Lua 语法高亮
    this->StyleSetForeground(wxSTC_LUA_DEFAULT, wxColour(0, 0, 0));
    this->StyleSetForeground(wxSTC_LUA_COMMENT, wxColour(0, 127, 0));
    this->StyleSetForeground(wxSTC_LUA_COMMENTLINE, wxColour(0, 127, 0));
    this->StyleSetForeground(wxSTC_LUA_NUMBER, wxColour(0, 0, 127));
    this->StyleSetForeground(wxSTC_LUA_WORD, wxColour(0, 0, 255));  // 关键字
    this->StyleSetForeground(wxSTC_LUA_WORD2, wxColour(0, 128, 192));  // 函数名
    this->StyleSetForeground(wxSTC_LUA_WORD3, wxColour(128, 0, 255));
    this->StyleSetForeground(wxSTC_LUA_WORD4, wxColour(0, 0, 160));
    this->StyleSetForeground(wxSTC_LUA_WORD5, wxColour(210, 105, 30));
    this->StyleSetForeground(wxSTC_LUA_WORD6, wxColour(165, 42, 42));
    this->StyleSetForeground(wxSTC_LUA_STRING, wxColour(255, 0, 0));
    this->StyleSetForeground(wxSTC_LUA_CHARACTER, wxColour(255, 0, 0));
    this->StyleSetForeground(wxSTC_LUA_LITERALSTRING, wxColour(222, 0, 0));
    this->StyleSetForeground(wxSTC_LUA_STRINGEOL, wxColour(111, 0, 0));
    this->StyleSetForeground(wxSTC_LUA_OPERATOR, wxColour(0, 0, 160));
    this->StyleSetForeground(wxSTC_LUA_PREPROCESSOR, wxColour(255, 0, 0));

    this->StyleSetBold(wxSTC_LUA_WORD, true);
    this->StyleSetBold(wxSTC_LUA_NUMBER, true);

    // 设置关键字
    this->SetKeyWords(0, "and break do else elseif end for function if in local nil not or repeat return then until while false true goto");
    this->SetKeyWords(1, "assert collectgarbage dofile error _G getmetatable ipairs loadfile next pairs pcall print rawequal rawget rawset setmetatable tonumber tostring type _VERSION xpcall string table math coroutine io os debug getfenv gcinfo load loadlib loadstring require select setfenv unpack _LOADED LUA_PATH _REQUIREDNAME package rawlen package bit32 utf8 _ENV");
    this->SetKeyWords(2, "string.byte string.char string.dump string.find string.format string.gsub string.len string.lower string.rep string.sub string.upper table.concat table.insert table.remove table.sort math.abs math.acos math.asin math.atan math.atan2 math.ceil math.cos math.deg math.exp math.floor math.frexp math.ldexp math.log math.max math.min math.pi math.pow math.rad math.random math.randomseed math.sin math.sqrt math.tan string.gfind string.gmatch string.match string.reverse string.pack string.packsize string.unpack table.foreach table.foreachi table.getn table.setn table.maxn table.pack table.unpack table.move math.cosh math.fmod math.huge math.log10 math.modf math.mod math.sinh math.tanh math.maxinteger math.mininteger math.tointeger math.type math.ult bit32.arshift bit32.band bit32.bnot bit32.bor bit32.btest bit32.bxor bit32.extract bit32.replace bit32.lrotate bit32.lshift bit32.rrotate bit32.rshift utf8.char utf8.charpattern utf8.codes utf8.codepoint utf8.len utf8.offset");
    this->SetKeyWords(3, "coroutine.create coroutine.resume coroutine.status coroutine.wrap coroutine.yield io.close io.flush io.input io.lines io.open io.output io.read io.tmpfile io.type io.write io.stdin io.stdout io.stderr os.clock os.date os.difftime os.execute os.exit os.getenv os.remove os.rename os.setlocale os.time os.tmpname coroutine.isyieldable coroutine.running io.popen module package.loaders package.seeall package.config package.searchers package.searchpath require package.cpath package.loaded package.loadlib package.path package.preload");
    this->SetKeyWords(4, "system nodemanager wxString locomanager guimanager");

    InitLuaEditorWithFolding(this);
}

void MainScriptEditor::InitLuaEditorWithFolding(wxStyledTextCtrl* ctrl)
{
    // 设置折叠
    SetupLuaFolding(ctrl);

    // 绑定折叠事件
    /*ctrl->Bind(wxEVT_STC_MARGINCLICK, [](wxStyledTextEvent& event) {
        wxStyledTextCtrl* ctrl = dynamic_cast<wxStyledTextCtrl*>(event.GetEventObject());
        if (ctrl && event.GetMargin() == 2) {  // 确保点击的是折叠边距
            int line = event.GetLine();
            ctrl->ToggleFold(line);
        }
        event.Skip();
    });*/

    // 初始折叠设置
    ctrl->Colourise(0, -1);
    SetLuaFoldLevels(ctrl);
}

void MainScriptEditor::SetLuaFoldLevels(wxStyledTextCtrl* ctrl)
{
    int level = wxSTC_FOLDLEVELBASE;
    int lineCount = ctrl->GetLineCount();
    std::stack<int> foldLevels;

    for (int line = 0; line < lineCount; line++) {
        int lineStart = ctrl->PositionFromLine(line);
        int lineEnd = ctrl->PositionFromLine(line + 1);
        wxString text = ctrl->GetTextRange(lineStart, lineEnd).Trim();

        // 跳过空行和注释
        if (text.empty() || text.StartsWith("--")) {
            ctrl->SetFoldLevel(line, level | wxSTC_FOLDLEVELWHITEFLAG);
            continue;
        }

        // 检测块开始关键字
        if (text.StartsWith("function ") || text.StartsWith("if ") ||
            text.StartsWith("for ") || text.StartsWith("while ") ||
            text.StartsWith("repeat")) {
            // 设置折叠头
            ctrl->SetFoldLevel(line, wxSTC_FOLDLEVELHEADERFLAG + level);
            foldLevels.push(level);
            level++;
        }
        // 检测块结束关键字
        else if (text == "end" || text.StartsWith("until ")) {
            if (!foldLevels.empty()) {
                level = foldLevels.top();
                foldLevels.pop();
            }
            ctrl->SetFoldLevel(line, level);
        }
        // 普通行
        else {
            ctrl->SetFoldLevel(line, level);
        }
    }

    ctrl->Colourise(0, -1);
}

void MainScriptEditor::SetupLuaFolding(wxStyledTextCtrl* ctrl)
{
    // 启用折叠功能
    ctrl->SetProperty("fold", "1");
    ctrl->SetProperty("fold.compact", "1");
    ctrl->SetFoldFlags(wxSTC_FOLDFLAG_LINEBEFORE_CONTRACTED | wxSTC_FOLDFLAG_LINEAFTER_CONTRACTED);

    // 设置折叠标记样式
    ctrl->SetMarginType(2, wxSTC_MARGIN_SYMBOL);
    ctrl->SetMarginMask(2, wxSTC_MASK_FOLDERS);
    ctrl->SetMarginWidth(2, 16);
    ctrl->SetMarginSensitive(2, true);  // 确保边距可点击

    // 定义颜色常量
    const wxColour FOLD_MARK_COLOR(240, 240, 240);   // 深灰色用于标记符号
    const wxColour FOLD_BG_COLOR(150, 150, 150);     // 浅灰色背景
    const wxColour FOLD_LINE_COLOR(200, 200, 200);   // 更浅的灰色用于连接线

    // 设置折叠标记样式 - Notepad++风格
    ctrl->MarkerDefine(wxSTC_MARKNUM_FOLDEROPEN, wxSTC_MARK_BOXMINUS, FOLD_MARK_COLOR, FOLD_BG_COLOR);
    ctrl->MarkerDefine(wxSTC_MARKNUM_FOLDER, wxSTC_MARK_BOXPLUS, FOLD_MARK_COLOR, FOLD_BG_COLOR);
    ctrl->MarkerDefine(wxSTC_MARKNUM_FOLDERSUB, wxSTC_MARK_VLINE, FOLD_LINE_COLOR, FOLD_BG_COLOR);
    ctrl->MarkerDefine(wxSTC_MARKNUM_FOLDERTAIL, wxSTC_MARK_LCORNER, FOLD_LINE_COLOR, FOLD_BG_COLOR);
    ctrl->MarkerDefine(wxSTC_MARKNUM_FOLDEREND, wxSTC_MARK_BOXPLUSCONNECTED, FOLD_MARK_COLOR, FOLD_BG_COLOR);
    ctrl->MarkerDefine(wxSTC_MARKNUM_FOLDEROPENMID, wxSTC_MARK_BOXMINUSCONNECTED, FOLD_MARK_COLOR, FOLD_BG_COLOR);
    ctrl->MarkerDefine(wxSTC_MARKNUM_FOLDERMIDTAIL, wxSTC_MARK_TCORNER, FOLD_LINE_COLOR, FOLD_BG_COLOR);

    // 可选：设置边距背景色以匹配Notepad++风格
    /*ctrl->SetFoldMarginColour(true, FOLD_BG_COLOR);
    ctrl->SetFoldMarginHiColour(true, FOLD_BG_COLOR);

    // 设置折叠标记的颜色和样式
    ctrl->MarkerDefine(wxSTC_MARKNUM_FOLDEROPEN, wxSTC_MARK_BOXMINUS, *wxBLACK, *wxBLACK);
    ctrl->MarkerDefine(wxSTC_MARKNUM_FOLDER, wxSTC_MARK_BOXPLUS, *wxBLACK, *wxBLACK);
    ctrl->MarkerDefine(wxSTC_MARKNUM_FOLDERSUB, wxSTC_MARK_VLINE, *wxBLACK, *wxBLACK);
    ctrl->MarkerDefine(wxSTC_MARKNUM_FOLDERTAIL, wxSTC_MARK_LCORNER, *wxBLACK, *wxBLACK);
    ctrl->MarkerDefine(wxSTC_MARKNUM_FOLDEREND, wxSTC_MARK_BOXPLUSCONNECTED, *wxBLACK, *wxBLACK);
    ctrl->MarkerDefine(wxSTC_MARKNUM_FOLDEROPENMID, wxSTC_MARK_BOXMINUSCONNECTED, *wxBLACK, *wxBLACK);
    ctrl->MarkerDefine(wxSTC_MARKNUM_FOLDERMIDTAIL, wxSTC_MARK_TCORNER, *wxBLACK, *wxBLACK);  */

    // 设置折叠标志
    ctrl->SetFoldFlags(wxSTC_FOLDFLAG_LINEBEFORE_CONTRACTED | wxSTC_FOLDFLAG_LINEAFTER_CONTRACTED);
}

void MainScriptEditor::OnMarginClick(wxStyledTextEvent& event)
{
    wxStyledTextCtrl* ctrl = dynamic_cast<wxStyledTextCtrl*>(event.GetEventObject());
    if (ctrl && event.GetMargin() == 2) {  // 确保点击的是折叠边距
        wxPoint pos = ctrl->ScreenToClient(wxGetMousePosition());
        int line = ctrl->LineFromPosition(ctrl->PositionFromPoint(pos));

        ctrl->ToggleFold(line);
    }

    event.Skip();
}

void MainScriptEditor::OnMouseMove(wxMouseEvent& event) {
    // 获取鼠标位置
    int pos = PositionFromPoint(event.GetPosition());

    if (pos != wxSTC_INVALID_POSITION) {
        // 获取单词开始和结束位置
        int wordStart = WordStartPosition(pos, true);
        int wordEnd = WordEndPosition(pos, true);

        // 获取单词文本
        wxString word = GetTextRange(wordStart, wordEnd);

        if(word != "" && m_currentHoverString != word)
        {
            m_currentHoverString = word;
            m_hoverTimer.StartOnce(1000);
        }
        else
        {
            m_currentHoverString = "";
            this->CallTipCancel();
            m_hoverTimer.Stop();
        }
    }

    event.Skip();
}

void MainScriptEditor::OnHoverTimer(wxTimerEvent& event)
{
    wxPoint currentPos = ScreenToClient(wxGetMousePosition());
    int pos = PositionFromPoint(currentPos);

    if (pos != wxSTC_INVALID_POSITION && m_currentHoverString != "")
    {
        std::string paramInfo = LuaAnalyzer::getSingleton().getParamInfo(m_currentHoverString.ToStdString());
        if(paramInfo != "")
        {
            std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
            this->CallTipShow(pos,converter.from_bytes(paramInfo));
            this->CallTipSetPosition(true);
        }
    }
}

void MainScriptEditor::OnCharAdded(wxStyledTextEvent& event)
{
    int key = event.GetKey();

    // 当输入 '.' 或 ':' 时触发自动补全
    if (key == '.' || key == ':') {
        // 获取当前行的文本
        int currentPos = this->GetCurrentPos();
        int lineStart = this->PositionFromLine(this->LineFromPosition(currentPos));
        wxString lineText = this->GetTextRange(lineStart, currentPos);
        if(lineText != "")
        {
            int pos = lineText.find_last_of(" ");
            if(pos > 0)
                lineText = lineText.Mid(pos+1,lineText.length());
            pos = lineText.find_last_of("(");
            if(pos > 0)
                lineText = lineText.Mid(pos+1,lineText.length());

            lineText = lineText.Mid(0,lineText.length()-1);
        }        

        ObjectInfo* pObjectInfo = LuaAnalyzer::getSingleton().getObjectInfo(lineText.ToStdString());
        if(pObjectInfo != NULL)
        {
            std::vector<std::string> allparams = pObjectInfo->getAllParamName(key == ':' ? 0 : 1);
            if(!allparams.empty())
            {
                wxString decParams;
                for(int i=0;i<allparams.size();i++)
                    decParams += wxString::Format("%s ",allparams[i].c_str());

                // 这里可以解析上下文，提供更智能的补全
                this->AutoCompShow(0,decParams.Mid(0,decParams.length()-1));
            }
        }
        else
        {
            std::map<std::string,LuaAnalyzer::Variable> allvariables = LuaAnalyzer::getSingleton().getVariables();
            std::map<std::string,LuaAnalyzer::Variable>::iterator iter = allvariables.find(lineText.ToStdString());
            if(iter != allvariables.end())
            {
                pObjectInfo = LuaAnalyzer::getSingleton().getVariableInfo((*iter).second.type);
                if(pObjectInfo != NULL)
                {
                    std::vector<std::string> allparams;
                    if(pObjectInfo->inheritedclass != "")
                    {
                        ObjectInfo* pInheritedObjectInfo = LuaAnalyzer::getSingleton().getInheritedObjectInfo(pObjectInfo->inheritedclass);
                        if(pInheritedObjectInfo != NULL)
                        {
                            allparams = pInheritedObjectInfo->getAllParamName(key == ':' ? 0 : 1);
                        }
                    }

                    std::vector<std::string> allparams2 = pObjectInfo->getAllParamName(key == ':' ? 0 : 1);
                    allparams.insert(allparams.end(), allparams2.begin(), allparams2.end());

                    if(!allparams.empty())
                    {
                        wxString decParams;
                        for(int i=0;i<allparams.size();i++)
                            decParams += wxString::Format("%s ",allparams[i].c_str());

                        // 这里可以解析上下文，提供更智能的补全
                        this->AutoCompShow(0,decParams.Mid(0,decParams.length()-1));
                    }
                }
            }
        }
    }

    event.Skip();
}

void MainScriptEditor::OnAutocompCancelled(wxStyledTextEvent& event)
{
    event.Skip();
}

void MainScriptEditor::OnAutocompSelectionChange(wxStyledTextEvent& event)
{
    wxString selectedText = event.GetText();

    std::string paramInfo = LuaAnalyzer::getSingleton().getParamInfo(selectedText.ToStdString());
    if(paramInfo != "")
    {
        //std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;

        wxPoint currentPos = ScreenToClient(wxGetMousePosition());
        int pos = PositionFromPoint(currentPos);

        if (pos != wxSTC_INVALID_POSITION)
        {
            wxString decString = wxString::FromUTF8(paramInfo);
            decString.Replace("\n"," ");
            CMainFrame::getSingleton().printStatusBar(decString);
        }
    }

    event.Skip();
}

void MainScriptEditor::ClearAllHighlights()
{
    int indicatorNum = 8;
    this->SetIndicatorCurrent(indicatorNum);
    this->IndicatorClearRange(0, this->GetLength());
}

void MainScriptEditor::OnLeftDoubleClick(wxMouseEvent& event)
{
    m_isLeftBtnDoublieClick = true;
    event.Skip();
}

void MainScriptEditor::OnSelectionChanged(wxStyledTextEvent& event)
{
    wxString selectedText = this->GetSelectedText();
    if (!selectedText.IsEmpty() && m_isLeftBtnDoublieClick) {
        this->ClearAllHighlights();
        this->HighlightAllMatches(selectedText);
    }
    else
    {
        this->ClearAllHighlights();
    }
    m_isLeftBtnDoublieClick=false;


    if (m_isTextModified)
    {
        wxString modifiedLine = this->GetCurLine();

        using convert_type = std::codecvt_utf8<wchar_t>;
        std::wstring_convert<convert_type, wchar_t> converter;
        std::string resultContent = converter.to_bytes(UTF8ToGB2312(modifiedLine).wc_str());

        LuaAnalyzer::getSingleton().loadScriptFromString(resultContent);
        LuaAnalyzer::getSingleton().analyze();

        // 重置状态
        m_isTextModified = false;
    }

    event.Skip();
}

void MainScriptEditor::HighlightAllMatches(const wxString& text)
{
    if (text.IsEmpty()) return;

    int indicatorNum = 8;
    this->SetIndicatorCurrent(indicatorNum);

    int flags = wxSTC_FIND_MATCHCASE | wxSTC_FIND_WHOLEWORD; // 根据需要调整
    int startPos = 0;
    int endPos = this->GetLength();
    int textLen = text.length();

    this->SetSearchFlags(flags);
    this->SetTargetStart(startPos);
    this->SetTargetEnd(endPos);

    while (true) {
        int pos = this->SearchInTarget(text);
        if (pos == -1) break;

        int matchStart = this->GetTargetStart();
        int matchEnd = this->GetTargetEnd();

        // 应用高亮
        this->IndicatorFillRange(matchStart, matchEnd - matchStart);

        // 继续搜索
        this->SetTargetStart(matchEnd);
        this->SetTargetEnd(endPos);
    }
}

void MainScriptEditor::OnStyledTextModified(wxStyledTextEvent& event)
{
    int modificationType = event.GetModificationType();

    // 检查是否是文本插入或删除
    if (modificationType & (wxSTC_MOD_INSERTTEXT | wxSTC_MOD_DELETETEXT))
    {
        int line = this->LineFromPosition(event.GetPosition());
        m_lastModifiedLine = line;
        m_isTextModified = true;
    }
}

void MainScriptEditor::OnContentChange(wxStyledTextEvent& event)
{
    if(m_mainAuiNotebook == NULL || m_currentOperatorFile == "")
        return;

    wxString pTmpMd5Value = get_str_md5(this->GetText());

    int pPageIndex = m_mainAuiNotebook->GetPageIndex(this);
    if(pPageIndex >= 0)
    {
        wxString pageTitle;
        int pos = m_currentOperatorFile.find_last_of("/");
        pageTitle = (pos > 0 ? m_currentOperatorFile.Mid(pos+1) : m_currentOperatorFile);
        m_mainAuiNotebook->SetPageText(pPageIndex,
                                       pageTitle+(m_contentMd5Value != pTmpMd5Value ? "*" : ""));
    }
}

void MainScriptEditor::OnSize(wxSizeEvent& event)
{
    event.Skip();
}

wxString MainScriptEditor::LoadGB2312File(const wxString& filename)
{
    wxFile file(filename);
    if (!file.IsOpened()) return "";

    wxCSConv gb2312Conv(wxFONTENCODING_UTF8);
    char* buffer = (char*)allocBytes(file.Length() + 1);
    file.Read(buffer, file.Length());
    buffer[file.Length()] = '\0';

    wxString content(buffer, gb2312Conv);

    deallocBytes(buffer);
    file.Close();

    return content;
}

bool MainScriptEditor::SaveGB2312File(const wxString& filename,wxString content)
{
    wxFile file(filename, wxFile::write);
    if (!file.IsOpened())
        return false;

    wxCSConv gb2312Conv(wxFONTENCODING_UTF8);
    wxCharBuffer buffer = gb2312Conv.cWC2MB(content.wc_str());

    if (buffer.data()) {
        file.Write(buffer.data(), strlen(buffer.data()));
    }

    file.Close();
    return true;
}

bool MainScriptEditor::SaveFile(void)
{
    if(m_currentOperatorFile == "")
        return false;

    bool isOk = SaveGB2312File(m_currentOperatorFile,this->GetText());
    if(isOk)
    {
        int pPageIndex = m_mainAuiNotebook->GetPageIndex(this);
        if(pPageIndex >= 0)
        {
            wxString pageTitle;
            int pos = m_currentOperatorFile.find_last_of("/");
            pageTitle = (pos > 0 ? m_currentOperatorFile.Mid(pos+1) : m_currentOperatorFile);
            m_mainAuiNotebook->SetPageText(pPageIndex,pageTitle);
        }

        m_contentMd5Value = get_str_md5(this->GetText());
    }

    return isOk;
}

bool MainScriptEditor::LoadFile(const wxString& filename)
{
    if (filename == "" || !wxFileExists(filename)) return false;

    //wxStyledTextCtrl::LoadFile(filename);
    wxString deccontent = LoadGB2312File(filename);
    this->SetText(deccontent);
    m_contentMd5Value = get_str_md5(this->GetText());

    EmptyUndoBuffer();

    // 应用折叠
    SetLuaFoldLevels(this);

    using convert_type = std::codecvt_utf8<wchar_t>;
    std::wstring_convert<convert_type, wchar_t> converter;
    std::string resultContent = converter.to_bytes(deccontent.wc_str());

    LuaAnalyzer::getSingleton().loadScriptFromString(resultContent);
    LuaAnalyzer::getSingleton().analyze();

    //CMainFrame::getSingleton().printlog(LOG_LEVEL_INFO,LuaAnalyzer::getSingleton().printResults());

    return true;
}
